package com.xcity.game.item.operation;

import java.text.MessageFormat;

import com.xcity.db.entity.Player;
import com.xcity.game.common.AbstractConfirmOperation;
import com.xcity.game.common.Cause;
import com.xcity.game.common.MessageConst;
import com.xcity.game.item.ItemTemplate;
import com.xcity.pomelo.push.msg.TipPush;

public class SellItemOperation extends AbstractConfirmOperation {

	protected ItemTemplate template;
	protected long instanceId; // unique id
	protected int count;
	
	public SellItemOperation(Player player, ItemTemplate template, int count, String msg) {
		this(player, template, 0, count, msg);
	}
	
	public SellItemOperation(Player player, ItemTemplate template, long instanceId, int count, String msg) {
		super(player, msg);
		this.template = template;
		this.instanceId = instanceId;
		this.count = count;
	}

	@Override
	public void ok(Player player) {
		String error = sell(player, template, instanceId, count);
		if (error != null) {
			player.send(new TipPush(error));
		}
	}
	
	public static String sell(Player player, ItemTemplate template, long instanceId, int count) {
		if (instanceId != 0L) {
			if (player.getBag().removeItem(instanceId, count, Cause.SELL_ITEM) == null) {
				return MessageFormat.format(MessageConst.ITEM_NOT_ENOUGH, template.getName());
			}
		} else {
			if (!player.getBag().removeItem(template.getId(), count, Cause.SELL_ITEM)) {
				return MessageFormat.format(MessageConst.ITEM_NOT_ENOUGH, template.getName());
			}
		}
		
		int money = template.getPrice() * count;
		player.addGold(money, Cause.SELL_ITEM);
		return null;
	}
	
}
